<template>
  <div>
    <div>
      <div class="flex gap-3">
            <el-input placeholder="查询内容" v-model="query"></el-input>
            <el-button @click="doQuery">确认</el-button>
      <UButton @click="()=>{addModal=true}">新增</UButton>

        </div>
    </div>
    <UTable loading :loading-state="{ icon: 'i-heroicons-arrow-path-20-solid', label: 'Loading...' }"
            :progress="{ color: 'primary', animation: 'carousel' }" v-if="tableData" :rows="tableData"
            :columns="columns">
      <template #pic-data="{ row }">
        <img :src="row.pic" style="height: 40px;width: 40px">
      </template>
      <template #actions-data="{ row }">
        <!-- <span class=" hover:cursor-pointer">{{ row.actions }}</span> -->
        <UDropdown :items="items(row)">
          <UButton color="gray" variant="ghost" icon="i-heroicons-ellipsis-horizontal-20-solid"/>
        </UDropdown>
      </template>

    </UTable>

    <UModal v-model="addModal" :fullscreen="true" class="p-10">
      <el-form class="w-2/3 m-auto ">
        <el-form-item label="标题">
          <el-input v-model="addItem.name" ></el-input>
        </el-form-item>
        <el-form-item label="图片" >
          <el-upload v-model:file-list=addItem.fileList class="avatar-uploader" action="http://127.0.0.1:8000/other/upload"
                        :show-file-list="true" :on-success="(response, uploadFile, uploadFiles)=>{handleSuccess(response)}">
                        <img  v-if="addItem.pic" :src="addItem.pic" class="!h-40 !w-40 !rounded-2xl"><el-button type="primary">点击上传</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item label="标题">
          <el-select v-model="addItem.cate" placeholder="选择分类">
            <el-option label="有氧运动" value="有氧运动" />
            <el-option label="无氧运动" value="无氧运动" />
            <el-option label="球类运动" value="球类运动" />
            <el-option label="传统武术" value="传统武术" />
            <el-option label="户外活动" value="户外活动" />
          </el-select>
        </el-form-item>
        <el-form-item label="文本" >
      <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 300px; overflow-y: hidden;"
              v-model="addItem.content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
          </div>
          </el-form-item>
          <el-button @click="()=>{if(!isOpen){addOne(addItem)}else{updateOne(addItem);isOpen=false} addModal=false}" type="primary">确定</el-button>
      </el-form>
    </UModal>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted,reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
import axios from 'axios'
const editorRef = shallowRef()
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF:{
    uploadImage:{
      server:'http://localhost:8000/other/upload',
    async customUpload(file, insertFn) {                   // JS 语法
        // file 即选中的文件
        let formData = new FormData()
        formData.append('file',file)
        const res = await  axios.post('http://localhost:8000/other/upload',formData)

        insertFn(res.data.data, '', '')
    },
      customInsert(res, insertFn) {
        console.log("insert....")// JS 语法
          insertFn(res.data, '','' )
      },
    }
  }

}
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const addItem = reactive({
  name:'',
  content:'',
  pic:'',
  cate:''
})
const addModal = ref(false)


const toast = useToast()
let item = reactive({
  id: '', name: '', cate: '', content: '', pic: ''
})
let isOpen = ref(false)
let tableData = ref([])
const query = ref('')
function fuzzySearch(query, target) {
    return target.toLowerCase().includes(query.toLowerCase());
}
let _tableData =ref([])
const doQuery = ()=>{
 if(query.value!==''){
    let out = tableData.value.filter(item=>{
    let content = JSON.stringify(item)
    return fuzzySearch(query.value,content)
 })
 tableData.value = out
}else{
    tableData.value = _tableData.value
}
}
function getAll() {
  axios.post('http://localhost:8000/sport/get_one', {}).then(res => {
    let resp = res.data
    if (resp.code !== 200) {
      console.log(resp)
    } else {
      tableData.value = resp.data
      _tableData.value = resp.data
    }
  })
}

function addOne(item) {
  let payload = {
    'name':addItem.name,
    'content':addItem.content,
    'pic':addItem.pic,
    'cate':addItem.cate
  }
  axios.post("http://localhost:8000/sport/add_one",payload).then(res=>{
        let resp = res.data
    if (resp.code !== 200) {
      toast.add({
        icon: 'i-heroicons-information-circle-20-solid',
        title: '失败',
        color: 'red',
        // description: resp.msg,
      })
    } else {
      toast.add({
        icon: 'i-heroicons-information-circle-20-solid',
        title: '成功',
        // description: resp.msg,
      })
      getAll()
      addModal.value=false
    }
  }).then(()=>{
    addItem.value = {
            name:'',
      content:'',
      pic:'',
      cate:''
    }
  })


}
function deleteOne(item) {
  axios.post('http://localhost:8000/sport/delete_one', item).then(res => {
    let resp = res.data
    if (resp.code !== 200) {
      toast.add({
        icon: 'i-heroicons-information-circle-20-solid',
        title: '删除失败',
        color: 'red',
        // description: resp.msg,
      })
    } else {
      toast.add({
        icon: 'i-heroicons-information-circle-20-solid',
        title: '删除成功',
        // description: resp.msg,
      })
      getAll()
    }
  })
}
const handleSuccess = ( response) => {
  addItem.pic = response.data
    ElMessage.success('上传成功')
}

function updateOne(item) {
  axios.post('http://localhost:8000/sport/update_one', {'cond': {'id': item.id}, 'item': item}).then(res => {
    let resp = res.data
    if (resp.code !== 200) {
      toast.add({
        icon: 'i-heroicons-information-circle-20-solid',
        title: '更新失败',
        color: 'red',
        // description: resp.msg,
      })
    } else {
      toast.add({
        icon: 'i-heroicons-information-circle-20-solid',
        title: '更新成功',
        // description: resp.msg,
      })
      getAll()
      isOpen.value = false
    }
  }).then(()=>{
    addItem.value = {
            name:'',
      content:'',
      pic:'',
      cate:''
    }
  })
}

getAll()

const columns = [
  {'key': 'id', 'label': 'id'}, {'key': 'name', 'label': '标题'},
  {'key': 'cate', 'label': '分类'},
  {'key': 'pic', 'label': '封面'},
  {'key': 'actions', 'label': '操作'},
]

const items = (row) => [
  [{
    label: '修改',
    icon: 'i-heroicons-pencil-square-20-solid',
    click: () => {
      addModal.value = true
      isOpen.value = true
      addItem.id = row.id;
      addItem.name = row.name;
      addItem.cate = row.cate;
      addItem.content = row.content;
      addItem.pic  = row.pic
    }
  }, {
    label: '删除',
    icon: 'i-heroicons-trash-20-solid',
    click: () => {
      deleteOne(row)
    }
  }
  ]
]

</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

